<template>
  <el-card>
    <el-scrollbar always>
      <el-form class="search-card">
        <div class="search-input">
          <el-form-item label="店员名">
            <el-select v-model="clerkId" clearable placeholder="店员名" style="width:180px">
              <el-option
                  v-for="item in clerkNameList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="客户名">
            <el-input placeholder="请你输入客户名" v-model="customerName" clearable></el-input>
          </el-form-item>
        </div>
        <el-form-item>
          <el-button type="primary" size="default" @click="search" >搜索</el-button>
        </el-form-item>
      </el-form>
    </el-scrollbar>
  </el-card>
  <!--  展示数据-->
  <el-card>
    <el-button type="primary" size="default" @click="addCustomer">添加客户</el-button>
    <!--    展示客户信息-->
    <el-table  style="margin: 10px 0;" border :data="customerList">
      <el-table-column label="#" align="center" type="index"></el-table-column>
      <!--      <el-table-column label="ID" align="center" prop="id"></el-table-column>-->
      <el-table-column label="客户名" align="center" prop="name" show-overflow-tooltip></el-table-column>
      <el-table-column label="所属店员" align="center" prop="clerkName" show-overflow-tooltip></el-table-column>
      <el-table-column label="性别" align="center" prop="gender" show-overflow-tooltip>
        <template #="{ row, $index}">
          <p>{{row.gender === 0 ? "男":"女"}}</p>
        </template>
      </el-table-column>
      <el-table-column label="电话" align="center" prop="phone" show-overflow-tooltip></el-table-column>
      <el-table-column label="地址" align="center" prop="address" show-overflow-tooltip></el-table-column>
      <el-table-column label="生日" align="center" prop="birthday" show-overflow-tooltip>
        <template #="{ row }">
          <span>{{ getLocalTime(row.birthday, 1) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="notes" show-overflow-tooltip></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip>
        <template #="{ row }">
          <span>{{getLocalTime(row.createTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" show-overflow-tooltip>
        <template #="{ row }">
          <span>{{getLocalTime(row.updateTime, 1)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="banFlag" show-overflow-tooltip>
        <template #="{ row, $index}">
          <p v-if="row.banFlag === 0"></p>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200px" align="center">
        <template #="{ row, $index }">
          <el-row>
            <el-col :span="12">
              <el-button type="primary" size="small" icon="Edit" @click="updateCustomer(row)">编辑</el-button>
            </el-col>
            <el-col :span="12">
              <el-popconfirm :title="`你确定要删除${row.name}?`" width="260px" @confirm="deleteCustomer(row.id)">
                <template #reference>
                  <el-button type="primary" size="small" icon="Delete">删除</el-button>
                </template>
              </el-popconfirm>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-button type="warning" size="small" icon="Edit" @click="disableCustomer(row.id)">禁用</el-button>
            </el-col>
            <el-col :span="12">
              <el-button type="success" size="small" icon="Edit" @click="enableCustomer(row.id)">解禁</el-button>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
        @size-change="pageFn()"
        @current-change="pageFn"
        v-model:current-page="pn"
        v-model:page-size="ps"
        :page-sizes="[10, 20, 50, 100]"
        :background="true"
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="total"
    />
  </el-card>

  <el-dialog
      v-model="dialogFormVisible"
      :title="customerParams.id ? '修改客户' : '添加客户'"
  >
    <el-form style="width: 80%" :model="customerParams">
      <el-form-item label="客户名" label-width="100px" prop="name">
        <el-input v-model="customerParams.name"></el-input>
      </el-form-item>
      <el-form-item label="店员名" label-width="100px">
        <el-select v-model="customerParams.clerkId" clearable placeholder="店员名" style="width:180px">
          <el-option
              v-for="item in clerkNameList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="性别" label-width="100px" prop="gender">
        <el-radio-group v-model="customerParams.gender">
          <el-radio :value="0">男</el-radio>
          <el-radio :value="1">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="地址" label-width="100px" prop="address">
        <el-input v-model="customerParams.address"></el-input>
      </el-form-item>
      <el-form-item label="手机号" label-width="100px" prop="phone">
        <el-input v-model="customerParams.phone"></el-input>
      </el-form-item>
      <el-form-item label="生日" label-width="100px" prop="birthday">
        <el-date-picker
            v-model="customerParams.birthday"
            type="date"
            placeholder="生日"
            size="small"
        />
      </el-form-item>
      <el-form-item label="备注信息" label-width="100px" prop="notes">
        <el-input
            v-model="customerParams.notes"
            style="width: 240px"
            :rows="2"
            type="textarea"
            placeholder="备注信息"
        />
      </el-form-item>
    </el-form>
    <!-- 具名插槽:footer -->
    <template #footer>
      <el-button type="primary" size="default" @click="cancel">
        取消
      </el-button>
      <el-button type="primary" size="default" @click="save">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { reqNameList } from "@/api/personnel/clerk.js";
import * as APICustomer from "@/api/personnel/customer.js";
import { getLocalTime } from "@/utils/time.js";
import { ElMessage } from "element-plus";
import { onMounted, reactive, ref } from "vue";

/* ----- common ----- */
const clerkId = ref(null)
const clerkNameList = ref([])
const customerName = ref(null)

const pn = ref(1)
const ps = ref(10)
const total = ref(0)
//存储全部顾客的数组
const customerList = ref([])
//对话框可见性
const dialogFormVisible = ref(false)

//表单数据
let customerParams = reactive({
  id: null,
  clerkId: null,
  name: null,
  address: null,
  birthday: null,
  gender: null,
  phone: null,
  notes: null
})

// 获取全部客户数据, 默认第一页
const pageFn = async (pager = 1) => {
  // 默认第一页，应对删空最后一页问题
  pn.value = pager
  const result = await APICustomer.reqPageCustomer(
      pn.value,
      ps.value,
      clerkId.value,
      customerName.value,
  )
  // 一些时间处理
  if (result.code === '0') {
    total.value = result.data.total
    // customerList.value = []
    // result.data.items.forEach(item => {
    //   customerList.value.push(item)
    // })
    customerList.value = result.data.items
  }
}

// 组件挂载，获取下拉框数据和表格数据
onMounted(() => {
  reqNameList().then(resp => {
    clerkNameList.value = []
    resp.data.items.forEach(item => {
      clerkNameList.value.push({
        label: item.name,
        value: item.id,
      })
    })
  })
  pageFn()
})

//添加客户按钮
const addCustomer = () => {
  //显示对话框
  dialogFormVisible.value = true
  //清空表单数据
  Object.assign(customerParams,{
    id: null,
    clerkId: null,
    name: null,
    address: null,
    birthday: null,
    gender: null,
    phone: null,
    notes: null
  })
  //清除表单验证提醒（目前还没做）
}

// 更新客户信息
const updateCustomer = (row) => {
  //显示对话框
  dialogFormVisible.value = true
  //收集已有信息
  Object.assign(customerParams, row)
  //清除表单验证提醒（目前还没做）
}

//保存按钮的回调
const save = async () => {
  //表单验证（目前还没做）
  // 添加 | 更新信息
  let result
  if (customerParams.id) {
    //有id则为修改
    result = await APICustomer.reqUpdateCustomer(customerParams)
  } else {
    //无id则为添加
    result = await APICustomer.reqSaveCustomer(customerParams)
  }
  // 添加 | 更新成功
  if (result.code === '0') {
    ElMessage({message: customerParams.id? '修改成功' : '添加成功', type: 'success',})
    dialogFormVisible.value = false
    await pageFn()
  } else {
    dialogFormVisible.value = false
    //提示消息
    ElMessage({ type: 'error', message: customerParams.id ? '修改失败' : '添加失败' });
  }
}

//取消按钮的回调
const cancel = () => {
  //关闭对话框
  dialogFormVisible.value = false
}

//删除店长
const deleteCustomer = async (id) => {
  const result= await APICustomer.reqDeleteCustomerById(id)
  if (result.code === '0') {
    ElMessage({ type: 'success', message: '删除成功' })
    await pageFn(customerList.value.length > 1 ? pn.value : pn.value - 1);
  }
}

//禁用权限
const disableCustomer = async (id) => {
  const result = await APICustomer.reqDisableOrEnableCustomer(id,1)
  if (result.code === '0') {
    ElMessage({type: 'success', message: '禁用成功'})
    await pageFn()
  }
}

//启用
const enableCustomer = async (id) => {
  const result = await APICustomer.reqDisableOrEnableCustomer(id,0)
  if (result.code === '0') {
    ElMessage({type: 'success', message: '解禁成功'})
    await pageFn()
  }
}


//搜索按钮的回调
const search = () => {
  pageFn()
}
</script>

<style scoped lang="css">
.search-card {
  display: flex;
  align-items: center;
  flex-direction: row;
}
.search-input {
  display: flex;
  align-items: center;
  flex: 1 0 auto;
}
.search-input > * {
  flex: 0 1 auto;
  margin-right: 2rem;
}
.search-card .el-form-item {
  margin-bottom: 0;
}
.el-card {
  margin-bottom: 2rem;
}
</style>